/**
 * 
 */

package com.trydofor.id.test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : Shi Rongjiu (www.trydofor.com)
 */
public class MultiRunner {
    
    public static void runAsync(final Runnable task, int runs) {
        final CountDownLatch start = new CountDownLatch(1);
        ExecutorService es = Executors.newFixedThreadPool(runs);
        for (int i = 0; i < runs; i++) {
            es.execute(new Runnable() {
                
                @Override
                public void run() {
                    try {
                        start.await();
                        task.run();
                    }
                    catch (InterruptedException e) {}
                }
            });
        }
        start.countDown();
        es.shutdown();
    }
    
    public static void runSync(final Runnable task, int runs) {
        final CountDownLatch start = new CountDownLatch(1);
        final CountDownLatch done = new CountDownLatch(runs);
        ExecutorService es = Executors.newFixedThreadPool(runs);
        for (int i = 0; i < runs; i++) {
            es.execute(new Runnable() {
                
                @Override
                public void run() {
                    try {
                        start.await();
                        task.run();
                    }
                    catch (InterruptedException e) {}
                    finally{
                        done.countDown();
                    }
                }
            });
        }
        start.countDown();
        es.shutdown();
        try {
            done.await();
        }
        catch (InterruptedException e) {}
    }
}
